﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using 浏览器客户端.Models.Interfaces;
using 浏览器客户端.Models.Model;

namespace 浏览器客户端.Script
{
    public class IdCardReaderScript
    {
        private readonly string _module = "IdCardReaderScript";

        private Result<IIdCardReader> LoadDll()
        {
            try
            {
                var device = Config.Device.Devices.FirstOrDefault(e => e.Name == "身份证阅读器");
                if (device == null)
                {
                    return new Result<IIdCardReader>()
                    {
                        Code = 1,
                        Message = $"{_module}: 配置文件不存在"
                    };
                }

                var path = AppDomain.CurrentDomain.BaseDirectory + device.DllName;
                if (!File.Exists(path))
                {
                    return new Result<IIdCardReader>()
                    {
                        Code = 1,
                        Message = $"{_module}: DLL文件不存在"
                    };
                }

                var assembly = Assembly.LoadFile(path);
                var instance = assembly.CreateInstance($"{device.DllWorkSpace}.{device.DllClass}");
                if (instance != null && instance is IIdCardReader reader)
                {
                    return new Result<IIdCardReader>() { Data = reader };
                }
                return new Result<IIdCardReader>()
                {
                    Code = 1,
                    Message = $"{_module}: 无效的DLL文件"
                };
            }
            catch (Exception e)
            {
                return new Result<IIdCardReader>()
                {
                    Code = 1,
                    Message = $"{_module}: 加载DLL异常:{JsonConvert.SerializeObject(e)}"
                };
            }
        }

        public Result<Patient> ReadCard()
        {
            var result = LoadDll();
            if (result.Code != 200)
            {
                return new Result<Patient>()
                {
                    Code = 1,
                    Message = result.Message
                };
            }
            return new Result<Patient>()
            {
                Code = 200,
                Message = result.Message,
                Data = result.Data.ReadCard()
            };
        }
    }
}
